package com.buyi.easyhome.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.buyi.easyhome.worker.PlayTextWorker
import java.util.Date


class BatteryReceiver : BroadcastReceiver() {

    private val TAG = "BatteryReceiver"
    private var hasAlarmPct = 0
    private var lastedChargeFullSpeakTime: Long = 0

    override fun onReceive(context: Context, intent: Intent) {
        // 获取充电状态
        val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
        val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                || status == BatteryManager.BATTERY_STATUS_FULL
        Log.d(TAG, "onReceive: status: $status isCharging: $isCharging")

        // 获取电池电量
        val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)

        // 计算电池百分比
        val batteryPct = level * 100 / scale.toFloat()
        val batteryPctInt = batteryPct.toInt()
        Log.d(
            TAG,
            "onReceive: batteryPct: $batteryPct batteryPctInt: $batteryPctInt hasAlarmPct: $hasAlarmPct lastedChargeFullSpeakTime: $lastedChargeFullSpeakTime"
        )


        if (batteryPctInt < 40 && !isCharging) {

            // 已播报直接返回，未播报重置已播报的电量
            if (batteryPctInt == hasAlarmPct) {
                return
            } else {
                hasAlarmPct = 0
            }

            // 当电量低于30%且尚未播报过时，进行播报
            if (batteryPctInt <= 30 && batteryPctInt % 5 == 0) {
                var message = "电量$batteryPctInt，请注意充电。"
                if (batteryPctInt <= 20) message = "没电了，快充电。"

                alarmBattery(context, message + message)
                hasAlarmPct = batteryPctInt
            }

            return
        }

        if (batteryPctInt > 95 && isCharging) {

            if (batteryPctInt != 100) {
                lastedChargeFullSpeakTime = 0
                return
            }

            val now = Date().time
            // 间隔5分钟播报一次
            if (now - lastedChargeFullSpeakTime > 1000 * 60 * 5) {
                val message = "电充满了，电充满了。"
                alarmBattery(context, message)
                lastedChargeFullSpeakTime = now
            }

            return
        }

    }

    fun alarmBattery(context: Context, message: String) {
        WorkManager.getInstance(context)
            .enqueue(
                OneTimeWorkRequestBuilder<PlayTextWorker>()
                    .setInputData(
                        workDataOf(
                            "textToSpeechText" to message
                        )
                    )
                    .build()
            )
    }
}